package comm.net.cli;

import comm.net.protocol.Protocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ClientHandler extends ChannelInboundHandlerAdapter {
    private Client client;

    public ClientHandler(Client client) {
        this.client = client;
    }


	/**
	 * 连接时候
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {

        if (client.getSendProtocol() == null) {
            throw new NullPointerException();
        }

        ctx.writeAndFlush(client.getSendProtocol().getPro());
        super.channelActive(ctx);
	};
	
	/**
	 * 收到数据的时候
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        Protocol recvProtocol = new Protocol(obj);
	    client.setRecvProtocol(recvProtocol);
    }

	/**
	 * 发送异常的时候
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

}
